package czh.cocoa.ui.impl;

import czh.cocoa.animation.CABasicAnimation;
import czh.cocoa.animation.CALayer;
import czh.cocoa.animation.CATransformAction;
import czh.cocoa.graphics.CGRect;
import czh.cocoa.ui.UIImage;
import czh.cocoa.ui.UIView;

public class UIActivityIndicatorView extends UIImageView {
	
	public final static int UIActivityIndicatorViewStyleWhiteLarge = 0;
    public final static int UIActivityIndicatorViewStyleWhite = 1;
    public final static int UIActivityIndicatorViewStyleGray = 2;
	
    private boolean mHidesWhenStopped;
    
	public UIActivityIndicatorView(int style) {
		UIImage indicator;
		if (style == UIActivityIndicatorViewStyleWhiteLarge) {  
			indicator = UIImage.imageNamed(NSTR("cocoa/activity_indicator_large_white")); 
		} else if (style == UIActivityIndicatorViewStyleWhite) {
			indicator = UIImage.imageNamed(NSTR("cocoa/activity_indicator_white"));
		} else {
			indicator = UIImage.imageNamed(NSTR("cocoa/activity_indicator_gray"));
		}
		setImage(indicator);
		setFrame(CGRectMake(0, 0, indicator.size().width, indicator.size().height)); 
		mHidesWhenStopped = true;
	}
	
	public void startAnimating() {
		if (mHidesWhenStopped) {
			setHidden(false); 
		}
		CABasicAnimation anim = new CABasicAnimation(CALayer.ANIM_TRANSFORM); 
		CATransformAction transform = new CATransformAction();
		transform.rotateZ = 360;
		transform.scale = CGPointMake(0, 0);
		anim.setByValue(transform);
		anim.setDuration(1);
		anim.setRepeatCount(HUGE_VALF);
		layer().addAnimationForKey(anim, NSTR("rotating")); 
	}
	
	public void stopAnimating() {
		layer().removeAnimationForKey(NSTR("rotating"));
		if (mHidesWhenStopped) {
			setHidden(true); 
		}
	}
	
	public void setHidesWhenStopped(boolean stop) {
		mHidesWhenStopped = stop;
	}
	
	public boolean hidesWhenStopped() {
		return mHidesWhenStopped;
	}
	
}
